package com.sxf.biz.coordinator.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sxf.auth.enums.*;
import com.sxf.auth.login.model.AuthUser;
import com.sxf.auth.login.service.UserService;
import com.sxf.auth.login.vo.ChangePassWordReq;
import com.sxf.biz.coordinator.vo.*;
import com.sxf.biz.customer.dao.*;
import com.sxf.biz.customer.service.CustomerService;
import com.sxf.biz.customer.vo.*;
import com.sxf.biz.model.*;
import com.sxf.common.enums.ErrorCodeEnum;
import com.sxf.common.exceptions.BusinessException;
import com.sxf.consts.CodeTypeEnum;
import com.sxf.core.db.page.Pagination;
import com.sxf.utils.CodeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: TODO
 * @Author Leo
 * @date 2024/3/1820:22
 */
@Service
public class CoordinatorService {

    private static final Logger logger = LoggerFactory.getLogger(CoordinatorService.class);

    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    UserService userService;
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    CenterMapper centerMapper;
    @Autowired
    CustomerStaffMapper customerStaffMapper;
    @Autowired
    ProjectCenterMapper projectCenterMapper;
    @Autowired
    ProjectCenterSubjectsMapper projectCenterSubjectsMapper;
    @Autowired
    SettleMapper settleMapper;
    @Autowired
    ProjectCenterAuditMapper projectCenterAuditMapper;
    @Autowired
    ProjectCenterCoordinatorMapper projectCenterCoordinatorMapper;
    @Autowired
    CustomerService customerService;
    @Autowired
    CodeUtils codeUtils;
    @Autowired
    SettleStatusMapper settleStatusMapper;

    private static final Lock settleLock = new ReentrantLock();

    /**
     * 项目列表，一个协调员可能属于多个客户
     * @param req
     * @return
     */
    public Pagination<CoorProjectListRes> getProjectByPage(CoordinatorBaseReq req){
        QueryWrapper<CustomerStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerStaff::getPkUser,req.getUserId()).last("limit 1");
        CustomerStaff customerStaff = customerStaffMapper.selectOne(queryWrapper);
        if(customerStaff == null) {
            throw new BusinessException(ErrorCodeEnum.UNAUTHORIZED_ERROR);
        }
        return projectMapper.getProjectListByPage4Coor(new Pagination<>(req),req);
//        if(StaffTypeEnum.COORDINATOR.getCode().equals(customerStaff.getStaffType())){
//        }else{
//            return projectMapper.getProjectListByPage4Appr(new Pagination<>(req),req);
//        }
    }

    /**
     * 简化处理，一个协调员可能属于多个客户
     * @param req
     * @return
     */
    public CoorProjectDetailRes getProjectDetail(CoorProjectDetailReq req){
        QueryWrapper<CustomerStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerStaff::getPkUser,req.getUserId());
//        CustomerStaff customerStaff = customerStaffMapper.selectOne(queryWrapper);
//        if(customerStaff == null){
//            throw new BusinessException(ErrorCodeEnum.PROJECT_NOT_EXIST_ERROR);
//        }
//        req.setStaffType(customerStaff.getStaffType());
        CoorProjectDetailRes projectDetailByCooId = projectMapper.getProjectDetailByCooId(req);
        return projectDetailByCooId;
}


    public CoorCenterListRes getProjectBindedCenters(CoorProjectDetailReq req){
        Project project = projectMapper.selectById(req.getPkProject());
        if(project == null){
            throw new BusinessException(ErrorCodeEnum.PROJECT_NOT_EXIST_ERROR);
        }
        Customer customer = customerMapper.selectById(project.getPkCustomer());
        if(customer == null){
            throw new BusinessException(ErrorCodeEnum.CUSTOMER_NOT_EXIST_ERROR);
        }

        CoorCenterListRes res = new CoorCenterListRes();
        BeanUtils.copyProperties(project,res);
        res.setCustomerName(customer.getCustomerName());

        Pagination<CenterListRes> centerListBinded2Project = projectMapper.getCenterListBinded2Project(new Pagination<>(req), req);
        res.setCenterList(centerListBinded2Project);
        return res;
    }

    public Pagination<SubjectsListRes> getSubjectListBind2Center(CoorSubjectListReq req){
        Project project = projectMapper.selectById(req.getPkProject());
        if(project == null){
            throw new BusinessException(ErrorCodeEnum.PROJECT_NOT_EXIST_ERROR);
        }
        Center center = centerMapper.selectById(req.getPkCenter());
        if(center == null){
            throw new BusinessException(ErrorCodeEnum.CENTER_NOT_EXIST_ERROR);
        }

        Pagination<SubjectsListRes> centerListBinded2Project = projectMapper.getSubjectsListBinded2PrjCenter(new Pagination<>(req), req);

        return centerListBinded2Project;
    }

    public AddSubjectsRes addSubject2Center(AddSubjectsReq req){
        Project project = projectMapper.selectById(req.getPkProject());
        if(project == null){
            throw new BusinessException(ErrorCodeEnum.PROJECT_NOT_EXIST_ERROR);
        }
        Center center = centerMapper.selectById(req.getPkCenter());
        if(center == null){
            throw new BusinessException(ErrorCodeEnum.CENTER_NOT_EXIST_ERROR);
        }
        QueryWrapper<ProjectCenter> projectCenterQueryWrapper = new QueryWrapper<>();
        projectCenterQueryWrapper.lambda().eq(ProjectCenter::getPkProject,req.getPkProject())
                .eq(ProjectCenter::getPkCenter,req.getPkCenter());
        List<ProjectCenter> projectCenters = projectCenterMapper.selectList(projectCenterQueryWrapper);
        if(projectCenters == null || projectCenters.size() == 0){
            throw new BusinessException("该中心尚未绑定该项目");
        }

        validCoordinator(req.getUserId(),project.getPkProject(),center.getPkCenter());

        ProjectCentersSubjects pcs = new ProjectCentersSubjects();
        BeanUtils.copyProperties(req,pcs);
        pcs.setSubjectsCode(codeUtils.getCode(CodeTypeEnum.SUBJECTS));
        pcs.setCreator(req.getUserId());
        pcs.setCreatorName(req.getCurName());
        pcs.setCreatedTime(new Date());
        pcs.setBindStatus(ProjectBindStatusEnum.UNBIND.getCode());
        pcs.setProcessStatus(ProjectSubjectsProgressEnum.INPROGRESS.getCode());
        projectCenterSubjectsMapper.insert(pcs);
        AddSubjectsRes res = new AddSubjectsRes();
        res.setPkProjectCentersSub(pcs.getPkProjectCentersSub());
        return res;
    }

    public Boolean bindSubjects(BindSubjectsReq req){
        ProjectCentersSubjects projectCentersSubjects = projectCenterSubjectsMapper.selectById(req.getPkProjectCentersSub());
        if(projectCentersSubjects == null){
            throw new BusinessException("要绑定信息不存在");
        }
        if(ProjectBindStatusEnum.BIND.getCode().equals(projectCentersSubjects.getBindStatus())){
            throw new BusinessException("受试者已经绑定其它支付用户");
        }

        validCoordinator(req.getUserId(),projectCentersSubjects.getPkProject(),projectCentersSubjects.getPkCenter());

        QueryWrapper<ProjectCentersSubjects> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ProjectCentersSubjects::getPkProject,projectCentersSubjects.getPkProject())
                .eq(ProjectCentersSubjects::getPkUser,req.getPkUser())
                .ne(ProjectCentersSubjects::getProcessStatus,ProjectSubjectsProgressEnum.QUIT.getCode());
        Integer count = projectCenterSubjectsMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new BusinessException("该支付用户已经绑定其它受试者");
        }

        AuthUser user = userService.getById(req.getPkUser());
        if(user == null){
            throw new BusinessException(ErrorCodeEnum.USER_NOT_EXIST_ERROR);
        }
        projectCentersSubjects.setPkUser(req.getPkUser());
        projectCentersSubjects.setBindStatus(ProjectBindStatusEnum.BIND.getCode());
        projectCentersSubjects.setProcessStatus(ProjectSubjectsProgressEnum.INPROGRESS.getCode());
        projectCentersSubjects.setModifier(req.getUserId());
        projectCentersSubjects.setModifierName(req.getCurName());
        projectCentersSubjects.setModifiedTime(new Date());
        projectCenterSubjectsMapper.updateById(projectCentersSubjects);
        return true;
    }

    public Boolean editSubjects(CoorEditSubjectsReq req){
        ProjectCentersSubjects projectCentersSubjects = projectCenterSubjectsMapper.selectById(req.getPkProjectCentersSub());
        if(projectCentersSubjects == null){
            throw new BusinessException("受试者不存在");
        }
//        if(ProjectSubjectsProgressEnum.INPROGRESS.getCode().equals(projectCentersSubjects.getProcessStatus())
//                ||ProjectSubjectsProgressEnum.FINSIHED.getCode().equals(projectCentersSubjects.getProcessStatus())){
//            throw new BusinessException("不能修改当前受试者");
//        }

        validCoordinator(req.getUserId(),projectCentersSubjects.getPkProject(),projectCentersSubjects.getPkCenter());

        BeanUtils.copyProperties(req,projectCentersSubjects);
        projectCenterSubjectsMapper.updateById(projectCentersSubjects);
        return true;
    }

    public Boolean rebindSubjects(BindSubjectsReq req){

        ProjectCentersSubjects projectCentersSubjects = projectCenterSubjectsMapper.selectById(req.getPkProjectCentersSub());
        if(projectCentersSubjects == null){
            throw new BusinessException("受试者不存在");
        }
        validCoordinator(req.getUserId(),projectCentersSubjects.getPkProject(),projectCentersSubjects.getPkCenter());

//        if(ProjectSubjectsProgressEnum.INPROGRESS.getCode().equals(projectCentersSubjects.getProcessStatus())
//                ||ProjectSubjectsProgressEnum.FINSIHED.getCode().equals(projectCentersSubjects.getProcessStatus())){
//            throw new BusinessException("不能修改当前受试者");
//        }
        AuthUser user = userService.getById(req.getPkUser());
        if(user == null){
            throw new BusinessException(ErrorCodeEnum.USER_NOT_EXIST_ERROR);
        }

        QueryWrapper<ProjectCentersSubjects> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ProjectCentersSubjects::getPkProject,projectCentersSubjects.getPkProject())
                .eq(ProjectCentersSubjects::getPkUser,req.getPkUser())
                .ne(ProjectCentersSubjects::getProcessStatus,ProjectSubjectsProgressEnum.QUIT.getCode());
        Integer count = projectCenterSubjectsMapper.selectCount(queryWrapper);
        if(count > 0){
            throw new BusinessException("该支付用户已经绑定其它受试者");
        }

        projectCentersSubjects.setPkUser(req.getPkUser());
        projectCentersSubjects.setBindStatus(ProjectBindStatusEnum.BIND.getCode());
        projectCentersSubjects.setProcessStatus(ProjectSubjectsProgressEnum.INPROGRESS.getCode());
        projectCentersSubjects.setModifier(req.getUserId());
        projectCentersSubjects.setModifierName(req.getCurName());
        projectCentersSubjects.setModifiedTime(new Date());
        projectCenterSubjectsMapper.updateById(projectCentersSubjects);
        return true;
    }

    public Boolean quitProject(CoorProjectSubjectsDetaiReq req){
        ProjectCentersSubjects projectCentersSubjects = projectCenterSubjectsMapper.selectById(req.getPkProjectCentersSub());
        if(projectCentersSubjects == null){
            throw new BusinessException("受试者不存在");
        }

        validCoordinator(req.getUserId(),projectCentersSubjects.getPkProject(),projectCentersSubjects.getPkCenter());

//        if(ProjectSubjectsProgressEnum.INPROGRESS.getCode().equals(projectCentersSubjects.getProcessStatus())
//                ||ProjectSubjectsProgressEnum.FINSIHED.getCode().equals(projectCentersSubjects.getProcessStatus())){
//            throw new BusinessException("不能修改当前受试者");
//        }
        projectCentersSubjects.setModifier(req.getUserId());
        projectCentersSubjects.setModifierName(req.getCurName());
        projectCentersSubjects.setModifiedTime(new Date());
        projectCentersSubjects.setProcessStatus(ProjectSubjectsProgressEnum.QUIT.getCode());
        projectCenterSubjectsMapper.updateById(projectCentersSubjects);
        return true;
    }

    public Pagination<CoorSettleListRes> getSettleListByPage(CoorSettleListReq req){
        QueryWrapper<CustomerStaff> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomerStaff::getPkUser,req.getUserId()).last("limit 1");
        CustomerStaff customerStaff = customerStaffMapper.selectOne(queryWrapper);
        if(customerStaff == null) {
            throw new BusinessException(ErrorCodeEnum.UNAUTHORIZED_ERROR);
        }
        if(StaffTypeEnum.COORDINATOR.getCode().equals(customerStaff.getStaffType())){
            //协调员
            return settleMapper.getSettleList4Coor(new Pagination<>(req),req);
        }else{
            if(CommonStatusEnum.VALID.getCode().equals(req.getWaitingApproval())){
                //带我审批
                return settleMapper.getSettleList4AduitWithApproval(new Pagination<>(req),req);
            }else{
                //所有
                return settleMapper.getSettleList4Aduit(new Pagination<>(req),req);
            }
        }
    }

    public CoorSettleDetailRes getSettleDetail(CoorSettleDetailReq req) {
        CoorSettleDetailRes settleDetail4Coor = settleMapper.getSettleDetail4Coor(req);
        if(settleDetail4Coor != null){
            if(!StringUtils.isEmpty(settleDetail4Coor.getImgs())){
                String[] pics = settleDetail4Coor.getImgs().split(";");
                settleDetail4Coor.setImgList(Arrays.asList(pics));
            }
            SettleDetailReq sdr = new SettleDetailReq();
            sdr.setPkSettle(req.getPkSettle());
            List<SettleStatusVo> settleStatus = customerService.getSettleStatus(sdr);
            settleDetail4Coor.setSettleStatus(settleStatus);
        }
        return settleDetail4Coor;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean addSettle(CoorAddSettleReq req) {
        settleLock.lock();
        try{
            ProjectCentersSubjects projectCentersSubjects = projectCenterSubjectsMapper.selectById(req.getPkProjectCentersSub());
            if(projectCentersSubjects == null){
                throw new BusinessException("受试者不存在");
            }
            if(ProjectBindStatusEnum.UNBIND.getCode().equals(projectCentersSubjects.getBindStatus())){
                throw new BusinessException("尚未绑定受试者");
            }
            if(ProjectSubjectsProgressEnum.QUIT.getCode().equals(projectCentersSubjects.getProcessStatus())){
                throw new BusinessException("受试者已退出");
            }


            Center center = centerMapper.selectById(projectCentersSubjects.getPkCenter());
            if(center == null){
                throw new BusinessException(ErrorCodeEnum.CENTER_NOT_EXIST_ERROR);
            }

            validCoordinator(req.getUserId(),projectCentersSubjects.getPkProject(),projectCentersSubjects.getPkCenter());
            QueryWrapper<ProjectCenter> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ProjectCenter::getPkProject,projectCentersSubjects.getPkProject())
                    .eq(ProjectCenter::getPkCenter,projectCentersSubjects.getPkCenter());
            ProjectCenter projectCenter = projectCenterMapper.selectOne(queryWrapper);
            if(projectCenter  == null ){
                throw new BusinessException("该项目尚未绑定中心");
            }
            List<ProjectCenterCoordinatorAudit> projectCenterAudits = projectCenterMapper.getAuditList(projectCenter.getPkProjectCenter());
            if(projectCenterAudits == null ||projectCenterAudits.size() == 0 ){
                throw new BusinessException("没有配置相应的支付审核员");
            }
            Project project = projectMapper.selectById(projectCentersSubjects.getPkProject());

            if(PayTypeEnum.DETECTION.getCode().equals(req.getPayType())){
                if(req.getImgList() == null || req.getImgList().size() == 0){
                    throw new BusinessException("请上传检查费凭证");
                }
            }
            if(!PayTypeEnum.OTHERS.getCode().equals(req.getPayType())
                    && !PayTypeEnum.DETECTION.getCode().equals(req.getPayType()) ){
                if(req.getImgList() != null && req.getImgList().size() > 0){
                    throw new BusinessException("请不要上传图片凭证");
                }
            }

            Settle settle = new Settle();
            BeanUtils.copyProperties(req,settle);
            settle.setCreator(req.getUserId());
            settle.setCreatorName(req.getCurName());
            settle.setCreatedTime(new Date());
            settle.setStatus(SettleStatusEnum.CREATED.getCode());
            settle.setCoordinatorName(req.getCurName());
            settle.setPkCoordinator(req.getUserId());
            settle.setPkCenter(projectCentersSubjects.getPkCenter());
            settle.setCenterName(center.getCenterName());
            settle.setPkProject(projectCentersSubjects.getPkProject());
            settle.setProjectName(project.getProjectName());
            settle.setPkSubjects(projectCentersSubjects.getPkUser());
            settle.setCurrentApprover(projectCenterAudits.get(0).getPkUser());
            settle.setPkCustomer(projectCenter.getPkCustomer());
            settle.setSubjectsAlias(projectCentersSubjects.getSubjectsAlias());
            settle.setSubjectsCode(projectCentersSubjects.getSubjectsCode());
            settle.setSubjectsRandomNo(projectCentersSubjects.getSubjectsRandomNo());
            settle.setSubjectsSelectNo(projectCentersSubjects.getSubjectsSelectNo());

            if(req.getImgList() != null && req.getImgList().size() > 0){
                StringBuilder imgs = new StringBuilder();
                for (String img : req.getImgList()) {
                    imgs.append(img).append(";");
                }
                settle.setImgs(imgs.toString());
            }

            settleMapper.insert(settle);
            customerService.addSettleStatus(settle,req,req.getRemark());
        }finally {
            settleLock.unlock();
        }
        return true;
    }


    @Transactional(rollbackFor = Exception.class)
    public Boolean approveSettle(CoorSettleDetailReq req){
        Settle settle = settleMapper.selectById(req.getPkSettle());
        if(settle == null ){
            throw new BusinessException(ErrorCodeEnum.SETTLE_NOT_EXIST_ERROR);
        }
        if(!SettleStatusEnum.CHECKING.getCode().equals(settle.getStatus())
                && !SettleStatusEnum.CREATED.getCode().equals(settle.getStatus())){
            throw new BusinessException("结算单状态已变更,请刷新后重试");
        }

        if(!req.getUserId().equals(settle.getCurrentApprover())){
            throw new BusinessException("当前审批节点在等待其他人审批");
        }

        List<ProjectCenterAudit> nextApprovers = settleMapper.getNextApprover(req);
        if(nextApprovers == null || nextApprovers.size() == 0){
            throw new BusinessException("当前项目尚未添加审批人");
        }

        LambdaUpdateWrapper<Settle> updateWrapper = new LambdaUpdateWrapper<>();

        for(int i = 0 ; i < nextApprovers.size(); i++){
            if(nextApprovers.get(i).getAuditId().equals(settle.getCurrentApprover())){
                if(i < nextApprovers.size()-1){
                    updateWrapper.set(Settle::getCurrentApprover,nextApprovers.get(++i).getAuditId());
                    updateWrapper.set(Settle::getStatus,SettleStatusEnum.CHECKING.getCode());
                    settle.setStatus(SettleStatusEnum.CHECKING.getCode());
//                    settle.setCurrentApprover(nextApprovers.get(++i).getAuditId());
                    break;
                }else{
                    updateWrapper.set(Settle::getStatus,SettleStatusEnum.APPROVED.getCode());
                    updateWrapper.set(Settle::getCurrentApprover,null);
                    settle.setStatus(SettleStatusEnum.APPROVED.getCode());
//                    settle.setCurrentApprover(null);
                    break;
                }
            }
        }
        updateWrapper.set(Settle::getModifier,req.getUserId())
                .set(Settle::getModifierName,req.getCurName())
                .set(Settle::getModifiedTime,new Date())
                .eq(Settle::getPkSettle,settle.getPkSettle());
//        settle.setModifier(req.getUserId());
//        settle.setModifierName(req.getCurName());
//        settle.setModifiedTime(new Date());
        settleMapper.update(null,updateWrapper);

        customerService.addSettleStatus(settle,req,"审批通过");
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean rejectSettle(CoorRejectSettleReq req ){
        Settle settle = settleMapper.selectById(req.getPkSettle());
//        if(SettleStatusEnum.PAYED.getCode().equals(settle.getStatus())){
//            throw new BusinessException("结算单已付款，不能退回");
//        }
        if(!SettleStatusEnum.CHECKING.getCode().equals(settle.getStatus())
                && !SettleStatusEnum.CREATED.getCode().equals(settle.getStatus())){
            throw new BusinessException("结算单状态已变更,请刷新后重试");
        }
//        if(!SettleStatusEnum.CHECKING.getCode().equals(settle.getStatus())){
//            throw new BusinessException("结算单状态已变更,请刷新后重试");
//        }

        if(!req.getUserId().equals(settle.getCurrentApprover())){
            throw new BusinessException("当前审批节点在等待其他人审批");
        }

        UpdateWrapper<Settle> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(Settle::getStatus,SettleStatusEnum.REJECTED.getCode())
                .set(Settle::getCurrentApprover,null)
                .set(Settle::getRejectReason,req.getRejectReason())
                .set(Settle::getModifiedTime,new Date())
                .set(Settle::getModifier,req.getUserId())
                .set(Settle::getModifierName,req.getCurName())
                .eq(Settle::getPkSettle,settle.getPkSettle());
        settle.setStatus(SettleStatusEnum.REJECTED.getCode());
//        settle.setCurrentApprover(null);
//        settle.setRejectReason(req.getRejectReason());
//        settle.setModifierName(req.getCurName());
//        settle.setModifier(req.getUserId());
//        settle.setModifiedTime(new Date());
        settleMapper.update(null,updateWrapper);
        customerService.addSettleStatus(settle,req,req.getRejectReason());
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean editSettle(CoorEditSettleReq req){
        settleLock.lock();
        try{
            Settle settle = settleMapper.selectById(req.getPkSettle());
            if(settle == null){
                throw new BusinessException(ErrorCodeEnum.SETTLE_NOT_EXIST_ERROR);
            }
            if(!SettleStatusEnum.REJECTED.getCode().equals(settle.getStatus())
                    && !SettleStatusEnum.CREATED.getCode().equals(settle.getStatus())){
                throw new BusinessException(ErrorCodeEnum.SETTLE_STATUS_NOT_REJECT_ERROR);
            }

            validCoordinator(req.getUserId(),settle.getPkProject(),settle.getPkCenter());

            QueryWrapper<ProjectCenter> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ProjectCenter::getPkProject,settle.getPkProject())
                    .eq(ProjectCenter::getPkCenter,settle.getPkCenter());
            ProjectCenter projectCenter = projectCenterMapper.selectOne(queryWrapper);
            if(projectCenter  == null ){
                throw new BusinessException("该项目尚未绑定中心");
            }
            List<ProjectCenterCoordinatorAudit> projectCenterAudits = projectCenterMapper.getAuditList(projectCenter.getPkProjectCenter());
            if(projectCenterAudits == null ||projectCenterAudits.size() == 0 ){
                throw new BusinessException("没有配置相应的支付审核员");
            }

            if(PayTypeEnum.DETECTION.getCode().equals(req.getPayType())){
                if(req.getImgList() == null || req.getImgList().size() == 0){
                    throw new BusinessException("请上传检查费凭证");
                }
            }
            if(!PayTypeEnum.OTHERS.getCode().equals(req.getPayType())
                    && !PayTypeEnum.DETECTION.getCode().equals(req.getPayType()) ){
                if(req.getImgList() != null && req.getImgList().size() > 0){
                    throw new BusinessException("请不要上传图片凭证");
                }
            }

            BeanUtils.copyProperties(req,settle);
            settle.setCurrentApprover(projectCenterAudits.get(0).getPkUser());
            settle.setStatus(SettleStatusEnum.CREATED.getCode());
            settle.setModifier(req.getUserId());
            settle.setModifierName(req.getCurName());
            settle.setModifiedTime(new Date());
            settle.setRejectReason("");
            if(req.getImgList() != null && req.getImgList().size() > 0){
                StringBuilder imgs = new StringBuilder();
                for (String img : req.getImgList()) {
                    imgs.append(img).append(";");
                }
                settle.setImgs(imgs.toString());
            }

            settleMapper.updateById(settle);
            customerService.addSettleStatus(settle,req,req.getRemark());
            return true;
        }finally {
            settleLock.unlock();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteSettle(CoorSettleDetailReq req){
        Settle settle = settleMapper.selectById(req.getPkSettle());
        if(settle == null){
            throw new BusinessException("结算单不存在");
        }

        if(!req.getUserId().equals(settle.getCreator())){
            throw new BusinessException("无权删除该结算单");
        }

        if(!SettleStatusEnum.CREATED.getCode().equals(settle.getStatus())){
            throw new BusinessException("结算单已经在审批流程中，不能被删除");
        }

        settleMapper.deleteById(req.getPkSettle());
        QueryWrapper<SettleStatus> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.lambda().eq(SettleStatus::getPkSettle,req.getPkSettle());
        settleStatusMapper.delete(deleteWrapper);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateCoorUserInfo(CoorUpdateUserInfoReq req){

        if(req.getNewPassword() != null && req.getOldPassword() != null){
            //修改密码
            ChangePassWordReq changePassWordReq = new ChangePassWordReq();
            BeanUtils.copyProperties(req,changePassWordReq);
            userService.changePassword(changePassWordReq);
        }
        if(!StringUtils.isEmpty(req.getSmoName())){
            //修改smo 信息
            QueryWrapper<CustomerStaff> customerStaffQueryWrapper = new QueryWrapper<>();
            customerStaffQueryWrapper.lambda().eq(CustomerStaff::getPkUser,req.getUserId());
            List<CustomerStaff> customerStaffs = customerStaffMapper.selectList(customerStaffQueryWrapper);
            if(customerStaffs != null && customerStaffs.size() > 0){
                if(!req.getSmoName().equals(customerStaffs.get(0).getSmoName())){
                    UpdateWrapper<CustomerStaff> customerUpdateWrapper = new UpdateWrapper<CustomerStaff>();
                    customerUpdateWrapper.lambda().set(CustomerStaff::getSmoName,req.getSmoName())
                            .set(CustomerStaff::getModifiedTime,new Date())
                            .set(CustomerStaff::getModifier,req.getUserId())
                            .set(CustomerStaff::getModifierName,req.getCurName())
                            .eq(CustomerStaff::getPkUser,req.getUserId());
                    customerStaffMapper.update(null,customerUpdateWrapper);
                }
            }
        }
        if(!StringUtils.isEmpty(req.getUserName())){
            //修改用户姓名
            AuthUser user = userService.getById(req.getUserId());
            if(!user.getUserName().equals(req.getUserName())){
                user.setUserName(req.getUserName());
                user.setModifiedTime(new Date());
                userService.updateById(user);
            }
        }
        return true;
    }

    public CoordinatorInfoRes getCoordinatorInfoByMobile(CoordinatorInfoReq req){
        CoordinatorInfoRes res = new CoordinatorInfoRes();
        QueryWrapper<AuthUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AuthUser::getUserMobile,req.getUserMobile())
                .eq(AuthUser::getUserType,UserTypeEnum.COORDINATE.getCode()).last("limit 1");
        AuthUser authUser = userService.getOne(queryWrapper);
        if(authUser != null){
            res.setUserMobile(authUser.getUserMobile());
            res.setPkUser(authUser.getPkUser());
            res.setUserName(authUser.getUserName());

            QueryWrapper<CustomerStaff> staffQueryWrapper = new QueryWrapper<>();
            staffQueryWrapper.lambda().eq(CustomerStaff::getPkUser,authUser.getPkUser()).last("limit 1");
            CustomerStaff customerStaff = customerStaffMapper.selectOne(staffQueryWrapper);
            if(customerStaff != null){
                res.setSmoName(customerStaff.getSmoName());
            }
        }
        return res;
    }

    private void validCoordinator(String pkUser,Long pkProject,Long pkCenter){
        CoordinatorValidatorReq req = new CoordinatorValidatorReq();
        req.setPkCenter(pkCenter);
        req.setPkProject(pkProject);
        req.setPkUser(pkUser);
        CoordinatorValidatorRes count = projectCenterMapper.valid(req);
        if(count.getCoorCount() == 0){
            throw new BusinessException("您不是该项目下对应中心的协调员");
        }
    }

}
